package logic

import (
	"context"
	"fmt"
	"host/inits"
	"host/model"

	"host/hostrpc/hostrpc"
	"host/hostrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *hostrpc.LoginRequest) (*hostrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	var user model.User

	inits.DB.Debug().Where("mobile=?", in.Mobile).Find(&user)

	result, _ := inits.Rdb.Get(l.ctx, "sendSms"+in.Mobile).Result()
	if result != in.SmsCode {
		return nil, fmt.Errorf("短信验证码错误")
	}

	if user.ID == 0 {
		m := model.User{

			Mobile:   in.Mobile,
			Password: in.Password,
		}
		inits.DB.Debug().Create(&m)
	} else {

		if user.Password != in.Password {
			return nil, fmt.Errorf("密码错误")
		}
	}
	return &hostrpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
